package com.zzxx.photograph.service.impl;

import com.zzxx.photograph.dao.CategoryDao;
import com.zzxx.photograph.dao.impl.CategoryDaoImpl;
import com.zzxx.photograph.domain.Category;
import com.zzxx.photograph.domain.Img;
import com.zzxx.photograph.domain.PageBean;
import com.zzxx.photograph.service.CategoryService;
import com.zzxx.photograph.util.JedisUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class CategoryServiceImpl implements CategoryService {
    private CategoryDao categoryDao = new CategoryDaoImpl();

    @Override
    public List<Category> findAll() {
        Jedis jedis = JedisUtil.getJedis();
        List<Category> list;
//      1. 从redis查询数据 list
        // 只能查出value
//        Set<String> category1 = jedis.zrange("category", 0, -1);
        Set<Tuple> set = jedis.zrangeWithScores("category1", 0, -1);
        if (set == null || set.size() == 0) {

//      1.1 list == null || list.size==0 第一次查询
//                从数据库中查
            list = categoryDao.findAll(); // cid cname
//      将数据保存到redis中 sortedset  key score value score value
            for (Category category : list) {
                jedis.zadd("category1", category.getCid(), category.getCname());
            }
        } else {
//      1.2 else  不是第一次查询
//                从redis查询的list返回
            list = new ArrayList<>();
            for (Tuple tuple : set) {
                // cid - tuple.getScore()
                // cname - tuple.getElement();
                Category category = new Category((int) tuple.getScore(), tuple.getElement());
                list.add(category);
            }
        }
        return list;
    }

    @Override
    public PageBean<Img> findImgByCid(int cid, int currentPage, int pageSize) {
        PageBean<Img> imgPageBean = new PageBean<>();
        int start = (currentPage - 1) * pageSize;
        List<Img> list = categoryDao.queryImgByCid(cid, start, pageSize);
        int totalCount = categoryDao.queryCountByCid(cid);
        int totalPage = (totalCount + pageSize - 1) / (pageSize);
        imgPageBean.setList(list);
        imgPageBean.setTotalPage(totalPage);
        imgPageBean.setPageSize(pageSize);
        imgPageBean.setCurrentPage(currentPage);
        imgPageBean.setTotalCount(totalCount);
        return imgPageBean;
    }

    @Override
    public int findCidImgByIid(int iid) {
        return categoryDao.findCidImgByIid(iid);
    }

    @Override
    public List<Img> findImgsByCid(int cid, int iid) {
        return categoryDao.findImgsByCid(cid, iid);
    }
}
